import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../layout/Index.vue'
import Login from '../views/Login'
import Dashboard from '../views/Dashboard'
import local from '@/utils/local.js'
import { asyncRouter } from './asyncRouter.js'

Vue.use(VueRouter)

// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Index',
    redirect: '/dashboard',
    component: Index,
    children: [
      // 后台首页
      {
        path: '/dashboard',
        component: Dashboard
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import(/* webpackChunkName: "error" */ '../views/Error')
  }
]

// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

const router = new VueRouter({
  routes
})

// 根据用户登录的信息，来判断和计算当前需要展示的路由
// 什么时候触发计算?(登录成功\刷新页面)
calcRouter()
export function calcRouter() {
  const role = local.get('role')
  if (!role) return
  const finaRoutes = filterR(asyncRouter.children, role)
  // console.log(finaRoutes)
  // !!!!! 最重要的一句话，就是把计算出来的路由合并到主路由中
  asyncRouter.children = finaRoutes
  // router.addRoutes([asyncRouter])
  router.addRoute(asyncRouter)

  // 2.0 计算动态展示的导航菜单
  const lastMenu = calcMenu(finaRoutes)
  // console.log(lastMenu)
  local.set('menu', JSON.stringify(lastMenu))
}

function calcMenu(arr) {
  return arr.filter(item => {
    if (item.hidden) {
      return false
    } else {
      if (item.children) {
        item.children = calcMenu(item.children)
      }
      return true
    }
  })
}

function filterR(arr, role) {
  // 过滤路由
  return arr.filter(item => {
    if (item.meta && item.meta.role) {
      if (item.children) {
        item.children = filterR(item.children, role)
      }
      return item.meta.role.includes(role)
    } else {
      // 没有标记的意味着，整项都保留
      return true
    }
  })
}

// 使用导航守卫完成登录拦截
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
